
#include "Tower.h"
#include "Bullet.h"
#include "Enemy.h"
#include "EntityManager.h"
#include "../../SGD Wrappers/CSGD_TextureManager.h"
#include <math.h>
#include <list>
using std::list;


//Constructor
Tower::Tower(void)
{
	this->x					= 0.0f;
	this->y					= 0.0f;
	this->velocityX			= 0.0f;
	this->velocityY			= 0.0f;
	this->rotation			= 0.0f;
	this->collisionRadius	= 1.0f;
	this->isAlive			= true;
	this->entityType		= ENTITY_TOWER;
	this->towerType			= TOWER_BASIC;
	this->cooldownDuration	= 0.5f;
	this->cooldownTimer		= 0.5f;
	this->ammoCurrent		= 10;
	this->ammoMax			= 10;
	this->textureID = CSGD_TextureManager::GetInstance()->LoadTexture(_T("../Resource/Graphics/PlaceholderImage.png"));
}


//Destructor
Tower::~Tower(void)
{
}


//Update
void Tower::Update(float dt)
{
	//Search for an enemy to shoot
	cooldownTimer -= dt;
	EntityManager* entityManager = entityManager->GetInstance();
	list<Entity*> entityList = entityManager->FindEntitiesInRange(x, y, 500);
	list<Entity*>::iterator iterator;
	if (entityList.size() > 0)
	{
		for (iterator = entityList.begin(); iterator != entityList.end(); ++iterator)
		{
			Entity* e = (*iterator);
			if (e->entityType == ENTITY_ENEMY)
			{
				float vectorToTargetX = e->x - x;
				float vectorToTargetY = e->y - y;
				rotation = atan2(vectorToTargetY, vectorToTargetX) + 3.141f * 0.5f;
				if (cooldownTimer <= 0.0f)
				{
					cooldownTimer = cooldownDuration;
					Entity* newBullet = entityManager->CreateEntity(ENTITY_BULLET, x, y);
					dynamic_cast<Bullet*>(newBullet)->attackTarget = e;
					e->AddReference();
					float magnitude = sqrt(vectorToTargetX*vectorToTargetX + vectorToTargetY*vectorToTargetY);
					vectorToTargetX /= magnitude;
					vectorToTargetY	/= magnitude;
					newBullet->x += vectorToTargetX * 20.0f;
					newBullet->y += vectorToTargetY * 20.0f;
				}
				break;
			}
		}
	}
}


//Render
void Tower::Render()
{
	CSGD_TextureManager* TM = CSGD_TextureManager::GetInstance();
	RECT rect = {0, 0, 64, 64};
	POINT ptCenter = { (rect.right - rect.left) / 2, (rect.bottom - rect.top) / 2 };
	TM->Draw(textureID, (int)x - ptCenter.x, (int)y - ptCenter.y, 1.0f, 1.0f, &rect,
		(float)ptCenter.x, (float)ptCenter.y, rotation, D3DCOLOR_ARGB(255,255,255,255));

	TM->Draw(textureID, (int)x-3, (int)y-3, 0.1f, 0.1f, &rect, 32.0f, 32.0f, rotation, D3DCOLOR_ARGB(255,255,50,50));
}
